package com.selene.sqlSession;

import com.selene.config.BoundSql;
import com.selene.pojo.Configuration;
import com.selene.pojo.MappedStatement;
import com.selene.utils.GenericTokenParser;
import com.selene.utils.ParameterMapping;
import com.selene.utils.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

public class SimpleExecutor implements Executor {
    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        //use jdbc to query
        Connection connection = configuration.getDataSource().getConnection();
        //获取sql语句，转换占位符，识别占位符中属性
        String sql = mappedStatement.getSql();
        BoundSql boundSql = getBoundSql(sql);
        //获取预处理对象 prepared statement
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
        //设置参数
        String parameterType = mappedStatement.getParameterType();//获取到了参数的全路径（定义在xml中的）
        Class<?> parameterTypeClass = getClassType(parameterType);
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();
            Field declaredField = parameterTypeClass.getDeclaredField(content);
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[0]);
            preparedStatement.setObject(i + 1, o);
        }
        //执行sql
        if (mappedStatement.getResultType() == null) {
            preparedStatement.executeUpdate();
            return null;
        } else {
            ResultSet resultSet = preparedStatement.executeQuery();
            //封装结果集
            String resultType = mappedStatement.getResultType();
            Class<?> resultTypeClass = getClassType(resultType);
            ArrayList<Object> objects = new ArrayList<>();
            while (resultSet.next()) {
                ResultSetMetaData metaData = resultSet.getMetaData();
                Object o = resultTypeClass.getDeclaredConstructor().newInstance();
                for (int i = 1; i <= metaData.getColumnCount(); i++) {
                    //字段名
                    String columnName = metaData.getColumnName(i);
                    //字段值
                    Object value = resultSet.getObject(columnName);
                    //使用反射和内省，根据数据库表和实体的对应关系完成封装
                    PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                    Method writeMethod = propertyDescriptor.getWriteMethod();
                    writeMethod.invoke(o, value);
                }
                objects.add(o);
            }

            return (List<E>) objects;
        }
    }


    private Class<?> getClassType(String type) throws ClassNotFoundException {
        if (type != null) {
            Class<?> aClass = Class.forName(type);
            return aClass;
        } else {
            return null;
        }
    }

    /**
     * 解析占位符#{}中的值,并使用？代替，
     *
     * @param sql
     * @return
     */
    private BoundSql getBoundSql(String sql) {
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        //解析出来的sql
        String parsedSql = genericTokenParser.parse(sql);
        //解析出来的参数名称
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
        BoundSql boundSql = new BoundSql(parsedSql, parameterMappings);
        return boundSql;
    }
}
